//
//  SettingsViewController.m
//  Mid_Project
//
//  Created by 王世界 on 2020/11/27.
//

#import "SettingsViewController.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "PPBadgeView.h"
#import "AppDelegate.h"
#import "MyViewController.h"
#import "NoticeViewController.h"
#import "StorageViewController.h"
#import "PersonalViewController.h"
#import "ViewController.h"
#import "Single.h"

@interface SettingsViewController ()

@end

@implementation SettingsViewController



- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    NSString *url = @"http://172.18.178.56/api/user/login/pass";
    NSDictionary *parameters = @{@"name": [Single sharedInstance].wsj_name,
                                 @"password": [Single sharedInstance].wsj_password
    };
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    // 设置请求体为JSON
    manage.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置响应体为JSON
    manage.responseSerializer = [AFJSONResponseSerializer serializer];
    [manage POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress){} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[Single sharedInstance].datalist1 removeAllObjects];
        NSString *url2 = @"http://172.18.178.56/api/user/info/self";
        AFHTTPSessionManager *manage2 = [AFHTTPSessionManager manager];
        // 设置请求体为JSON
        manage2.requestSerializer = [AFJSONRequestSerializer serializer];
        // 设置响应体为JSON
        manage2.responseSerializer = [AFJSONResponseSerializer serializer];
        [manage2 GET:url2 parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress){} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *returndata = (NSDictionary*)responseObject;
            self.Data = [[NSDictionary alloc] init];
            self.Data = returndata;
            
            [[Single sharedInstance].datalist1 addObject:self.Data];
            
            [self.tableView reloadData];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
        NSString *url3 = @"http://172.18.178.56/api/notification/all";
        
        AFHTTPSessionManager *manage3 = [AFHTTPSessionManager manager];
        // 设置请求体为JSON
        manage3.requestSerializer = [AFJSONRequestSerializer serializer];
        // 设置响应体为JSON
        ((AFJSONResponseSerializer *)manage3.responseSerializer).removesKeysWithNullValues = YES;
        manage3.responseSerializer = [AFJSONResponseSerializer serializer];
        [manage3 GET:url3 parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress){} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *returndata = (NSDictionary*)responseObject;
            
            
            NSString *pd = [NSString stringWithFormat:@"%@",returndata[@"Notification"]];
            NSLog(@"%@",pd);
            if([pd isEqualToString:@"<null>"]){
                [self show_tableview];
                
                
                return;
            }
            
           
            self.Data2 = [[NSMutableArray alloc] init];
            self.Data2 = (NSMutableArray*)returndata[@"Notification"];
            
            [[Single sharedInstance].datalist1 addObject:self.Data2];
            
            NSString *s1;
            NSString *s2;
            for (int i = 0; i < self.Data2.count; i++) {
                s1 = [NSString stringWithFormat:@"%@",self.Data2[i][@"Data"][@"Read"]];
                s2 = [NSString stringWithFormat:@"%@",self.Data2[i][@"Data"][@"Type"]];
                if ([s1 isEqualToString:@"0"]) {
                    if ([s2 isEqualToString:@"reply"])
                        [Single sharedInstance].r_count++;
                    else
                        [Single sharedInstance].l_count++;
                }
            } [self show_tableview];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
}

-(void)show_tableview{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //注册cell(TablewViewcell的重用机制需要使用);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:@"reuse"];
    [self.view addSubview:_tableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 5;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) return 0;
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, 320,5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, 320,5)];
    view.backgroundColor = [UIColor clearColor];
//    [view.bounds];
    return view;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        UIImage * icon = [UIImage imageNamed:@"timg"];
        CGSize itemSize = CGSizeMake(50, 50);//固定图片大小为50*50
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0);//*1
        CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();//*2
        UIGraphicsEndImageContext();//*3
        cell.textLabel.text = _Data[@"Name"];
    }
    if (indexPath.section == 1) {
        UIImage * icon = [UIImage imageNamed:@"notice"];
        CGSize itemSize = CGSizeMake(32, 32);//固定图片大小为36*36
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0);//*1
        CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();//*2
        UIGraphicsEndImageContext();//*3
        cell.textLabel.text = @"通知";
        int n = [Single sharedInstance].r_count+[Single sharedInstance].l_count;
        
        if (n >= 99) {
            [cell pp_addBadgeWithNumber:99];
            
        }
        else {
            [cell pp_addBadgeWithNumber:n];
        }
        
        [cell pp_setBadgeHeight:25];
        [cell pp_moveBadgeWithX:-30 Y:25];
    }
    if (indexPath.section == 2) {
        UIImage * icon = [UIImage imageNamed:@"memory"];
        CGSize itemSize = CGSizeMake(32, 32);//固定图片大小为36*36
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0);//*1
        CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();//*2
        UIGraphicsEndImageContext();//*3
        cell.textLabel.text = @"存储";
    }
    if (indexPath.section == 3) {
        UIImage * icon = [UIImage imageNamed:@"setting"];
        CGSize itemSize = CGSizeMake(32, 32);//固定图片大小为36*36
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0);//*1
        CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();//*2
        UIGraphicsEndImageContext();//*3
        cell.textLabel.text = @"设置";
    }
    if (indexPath.section == 4) {
        _exit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [cell.contentView addSubview:_exit];
        [_exit mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(cell.contentView);
            make.centerX.equalTo(cell.contentView);
            make.width.equalTo(cell.contentView.mas_width).multipliedBy(1);
            make.height.equalTo(cell.contentView.mas_height).multipliedBy(1);
        }];
        _exit.backgroundColor = [UIColor redColor];
        [_exit setTitle:@"注销" forState:UIControlStateNormal];
        [_exit addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_exit setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
      
        cell.backgroundColor = [UIColor clearColor];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //跳转逻辑判断
    if(indexPath.section == 0) {
        MyViewController *my = [[MyViewController alloc]init];
        [self.navigationController pushViewController:my animated:YES];
        my.title = @"个人中心";
    }
    if(indexPath.section == 1) {
        NSLog(@"%d",[Single sharedInstance].datalist1.count);
        if([Single sharedInstance].datalist1.count == 2 ){
            NoticeViewController *notice = [[NoticeViewController alloc]init];
            [self.navigationController pushViewController:notice animated:YES];
            notice.title = @"通知";
            [self viewWillAppear:1];
        }
        
        
    }
    if(indexPath.section == 2) {
        StorageViewController *storage = [[StorageViewController alloc]init];
        [self.navigationController pushViewController:storage animated:YES];
        storage.title = @"存储";
    }
    if(indexPath.section == 3) {
        PersonalViewController *personal = [[PersonalViewController alloc]init];
        [self.navigationController pushViewController:personal animated:YES];
        personal.title = @"设置";
    }
    if(indexPath.section == 4) {
       
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 80;

    }
    else {
        return 50;
    }
  
}

-(void)buttonClicked:(id)sender{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    ViewController * vc = [[ViewController alloc]init];
    UINavigationController * root = [[UINavigationController alloc]initWithRootViewController:vc];
    app.window.rootViewController = root;
    
        [app.window makeKeyAndVisible];
    
}

@end
